package repository

import (
	"yak.admin/src/entity"
	"yak.admin/src/service"
	"yak.admin/src/util"
)

type DrugReportRepository struct {
}

func (repository *DrugReportRepository) StatusLabels() map[int]string {
	return map[int]string{
		util.PendingStatus: "待审核",
		util.FollowStatus:  "已关注",
		util.IgnoreStatus:  "已忽略",
	}
}

func (repository *DrugReportRepository) DrugCategoryLabels() map[int]string {
	var categories []*entity.DrugCategory
	db := util.GetMysqlPool().Handler()
	if db.Find(&categories).RecordNotFound() {
		return map[int]string{}
	}
	labels := make(map[int]string, len(categories))
	for _, m := range categories {
		labels[m.Id] = m.Name
	}
	return labels
}

func (repository *DrugReportRepository) DrugRiskLabels() map[int]string {
	var risks []*entity.DrugRisk
	db := util.GetMysqlPool().Handler()
	if db.Find(&risks).RecordNotFound() {
		return map[int]string{}
	}
	labels := make(map[int]string, len(risks))
	for _, m := range risks {
		labels[m.Id] = m.Name
	}
	return labels
}

func (repository *DrugReportRepository) FindReport(id uint) map[string]interface{} {
	report := entity.DrugReport{}
	reader := new(service.ReaderQuery).CreateModelQuery(&report).
		WithEQ("id", id).WithPreloads([]string{"Category", "DrugAnnexes", "Admin"})
	reader.One(&report)
	riskLabels := repository.DrugRiskLabels()
	return reader.Viewlist(&report, func(item interface{}) map[string]interface{} {
		m := item.(*entity.DrugReport)
		annexes := m.DrugAnnexes
		return map[string]interface{}{
			"number": m.Number,
			"title":    m.Title,
			"category": m.Category.Name,
			"risk":     reader.AsCheckListString(m.RiskRefer, riskLabels),
			"remark":   m.Remark,
			"unit":     m.Unit,
			"address":  m.Address,
			"phone":    m.Phone,
			"status":   m.Status,
			"comment":  m.Comment,
			"imgs":     reader.AsListImg(annexes, len(annexes), "Src"),
			"admin_avatar": util.GetImage(m.Admin.Avatar),
			"reported_at": reader.AsDatetime(m.ReportedAt),
		}
	})
}
